<?php

namespace App\Dao;

use App\Exceptions\SysExceptions;
use App\Model\RechargeOrderModel;
use Illuminate\Support\Facades\DB;

class RechargeDao extends BaseDao
{
    public static function builder_query($params = []): \Illuminate\Database\Eloquent\Builder
    {

        $query = RechargeOrderModel::query();

        $query->when(checkIsHasField($params,'order_sn'),function ($query)use ($params){
            $query->where('order_sn',$params['order_sn']);
        });
        $query->when(checkIsHasField($params,'u_recharge_id'),function ($query)use ($params){
            $query->where('u_recharge_id',$params['u_recharge_id']);
        });

        $query->when(checkIsHasField($params,'user_id'),function ($query)use ($params){
            $query->where('user_id',$params['user_id']);
        });

        $query->when(checkIsHasField($params,'status'),function ($query)use ($params){
            $query->where('status',$params['status']);
        });

        return $query->orderByDesc('created_at');
    }

    public static function pager(array $all): \Illuminate\Contracts\Pagination\LengthAwarePaginator
    {
        return self::builder_query($all)->paginate();
    }

    /**
     * @throws SysExceptions
     */
    public static function audit(array $params)
    {
        checkForData(['status'],['请选择审核状态'],$params);
        $info = self::builder_query([
            'u_recharge_id'=>$params['u_recharge_id']
        ])->first()->toArray();
        try {
            self::builder_query(['u_recharge_id'=>$params['u_recharge_id']])->update([
                'status'=>$params['status'],
                'memo'=>$params['memo']
            ]);
            if($params['status'] == 1){
                BillsDao::moneyUpdate($info['pay_usdt'],$info['user_id'],'充值成功');
            }
            DB::commit();
        }catch ( \Exception $exception){
            DB::rollBack();
            self::error($exception->getMessage());
        }

    }


}
